package com.telit.android.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.telit.android.constant.TaskMsgConstants;
import com.telit.android.dao.AppPatrolTrackDao;
import com.telit.android.dao.AppTaskDao;
import com.telit.android.dao.CommEventTaskTrackDao;
import com.telit.android.dto.*;
import com.telit.android.entity.AppPatrolTrack;
import com.telit.android.entity.AppTaskFeedback;
import com.telit.android.entity.AppUavTrackDetail;
import com.telit.android.feign.ThirdFeignClient;
import com.telit.android.service.IAppTaskService;
import com.telit.android.util.PatrolInfoUtil;
import com.telit.common.config.MessageFormatProperties;
import com.telit.common.constant.MsgConstants;
import com.telit.common.constant.NoticeTypeConstants;
import com.telit.common.core.utils.FeignUtils;
import com.telit.common.dto.NormalTaskDTO;
import com.telit.common.dto.SmsAddTaskDto;
import com.telit.common.entity.AppTask;
import com.telit.common.entity.CommEventTaskTrack;
import com.telit.common.entity.DataReturn;
import com.telit.common.entity.PageData;
import com.telit.common.enums.ResultCode;
import com.telit.common.exception.ForestBaseException;
import com.telit.common.pojo.AliPushContentPojo;
import com.telit.common.pojo.AliPushMessagePojo;
import com.telit.common.util.*;
import com.telit.firecommand.feign.RemoteFirecommandService;
import com.telit.uav.feign.RemoteUavService;
import com.telit.upms.feign.RemoteUpmsService;
import com.telit.upms.vo.MicroSysUserAllInfoVo;
import com.telit.upms.vo.MicroSysUserVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.telit.common.service.ParamsCheckService.*;
import static java.util.stream.Collectors.toList;


/**
 * <p>
 * 任务表 服务实现类
 * </p>
 *
 * @author yummy
 * @since 2021-07-22
 */
@Service
@Transactional
@Slf4j
@RequiredArgsConstructor
public class AppTaskServiceImpl extends ServiceImpl<AppTaskDao, AppTask> implements IAppTaskService {

    @Resource
    private CommEventTaskTrackDao commEventTaskTrackDao;

    @Autowired
    private MessageFormatProperties messageFormatProperties;

    @Autowired
    private AppTaskDao appTaskDao;

    @Autowired
    private AppPatrolTrackDao appPatrolTrackDao;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RemoteUavService uavFeignClient;

    @Autowired
    private RemoteFirecommandService fireCommandFeignClient;

    @Autowired
    private ThirdFeignClient thirdFeignClient;

    @Autowired
    private RemoteUpmsService remoteUpmsService;

    @Override
    public Long addHotportTrackTask(HotportTrackTaskDto hotportTrackTaskDto) throws Exception {
        Long start = System.currentTimeMillis();
        log.info("开始下达热点任务的逻辑，startTime:" + start);
        AppTask appTask = hotportTrackTaskDto.getAppTask();
        String hotPortNumberList = hotportTrackTaskDto.getHotPortNumberList();
        //获取用户ID
        Long userId = JwtTokenUtils.getId();
        appTask.setCreatePersonId(userId);
        //插入数据库
        baseMapper.insert(appTask);
        Long taskId = appTask.getId();
        Long first = System.currentTimeMillis();
        log.info("插入主任务表逻辑结束:insertTaskTable:" + (first - start));

        Map<String, List<Long>> countryToForestkeeperIdMap = hotportTrackTaskDto.getCountryToForestkeeperIdMap();
        List<CommEventTaskTrack> eventTaskTrackList = new ArrayList<>();
        List<Long> totalForestkeeperIdList = new ArrayList<>();
        //子任务添加
        subTask(eventTaskTrackList, totalForestkeeperIdList, countryToForestkeeperIdMap, hotPortNumberList, taskId);

        //获取系统管理员姓名
        String userName = JwtTokenUtils.getRealName();
        //格式化发送title和content
        String typeName = hotportTrackTaskDto.getTypeName();
        String title = formatMessage(messageFormatProperties.getTitleFormat(), typeName);
        String content = formatMessage(messageFormatProperties.getContentFormat(), userName, typeName);

        //子任务入库
        commEventTaskTrackDao.insertBatch(eventTaskTrackList);
        Long second = System.currentTimeMillis();
        log.info("插入子任务表逻辑结束:insertCommTaskTable:" + (second - first));

        // 记录消息中心
        fireCommandFeignClient.addBatch(new CommMsgCenterLogDTO(content, "1", new Date(), "1", userName, title,
                totalForestkeeperIdList));

        Long third = System.currentTimeMillis();
        log.info("记录消息,openfeign 远程调用耗时：" + (third - second));

        Map<String, Object> contentMap = new HashMap<>();
        contentMap.put("taskId", taskId);
        contentMap.put("content", content);
        List<String> totalForestkeeperIdStrList = Convert.toList(String.class, totalForestkeeperIdList);
        //消息推送
        AliyunPushMessageUtils.customizeAdvancedPush(
                new AliPushMessagePojo(MsgConstants.TARGET_ACCOUNT, MsgConstants.PUSH_TYPE_MESSAGE,
                        MsgConstants.DEVICE_TYPE_ANDROID, title, totalForestkeeperIdStrList,
                        new AliPushContentPojo(NoticeTypeConstants.NOTICE_TYPE_CENTER_MSG,
                                JSON.toJSONString(contentMap))));

        Long forth = System.currentTimeMillis();
        log.info("消息推送耗时:" + (forth - third));
        log.info("下达热点巡护任务总耗时：" + (forth - start));
        return taskId;
    }

    /**
     * 获取用户真实姓名
     *
     * @param userId
     *
     * @return
     */
    private String getRealNameFromFeign(Long userId) {
        //获取接收人数据集合
        com.telit.common.core.utils.Result<Map<Long, MicroSysUserVo>> selectByBatchIdsResult = remoteUpmsService.selectByBatchIds(
                Arrays.asList(userId), true);
        Map<Long, MicroSysUserVo> microSysUserVoMap = FeignUtils.unwrap(selectByBatchIdsResult);
        MicroSysUserVo microSysUserVo = microSysUserVoMap.get(userId);
        if (microSysUserVo == null) {
            throw new ForestBaseException(LanguageUtils.codeMessage(ResultCode.OPERATE_ERROR.getCode(), userId));
        }
        return microSysUserVo.getRealName();
    }

    private String formatMessage(String format, String... message) {
        String format1 = String.format(format, message);
        return format1;
    }

    private void subTask(List<CommEventTaskTrack> eventTaskTrackList, List<Long> totalForestkeeperIdList,
                         Map<String, List<Long>> countryToForestkeeperIdMap, String hotPortNumberList, Long taskId) {
        for (String countryCode : countryToForestkeeperIdMap.keySet()) {
            List<Long> forestkeeperIdList = countryToForestkeeperIdMap.get(countryCode);
            //加入总护林员ID集合
            totalForestkeeperIdList.addAll(forestkeeperIdList);
            //加入子任务集合
            for (Long forestkeeperId : forestkeeperIdList) {
                CommEventTaskTrack commEventTaskTrack = new CommEventTaskTrack().setHotPortNumber(
                        hotPortNumberList).setCountryCode(countryCode).setTaskId(taskId).setForestkeeperId(
                        forestkeeperId);
                eventTaskTrackList.add(commEventTaskTrack);
            }
        }
    }

    @Override
    public Long addHotportUavTask(HotportUavTaskDto hotportUavTaskDto) throws Exception {
        AppTask appTask = hotportUavTaskDto.getAppTask();
        //获取用户ID
        Long userId = JwtTokenUtils.getId();
        appTask.setCreatePersonId(userId);
        //插入数据库
        baseMapper.insert(appTask);
        Long taskId = appTask.getId();
        //获取系统管理员姓名
        String userName = JwtTokenUtils.getRealName();
        //格式化发送title和content
        String typeName = hotportUavTaskDto.getTypeName();
        String title = formatMessage(messageFormatProperties.getTitleFormat(), typeName);
        String content = formatMessage(messageFormatProperties.getContentFormat(), userName, typeName);

        Map<String, Object> contentMap = new HashMap<>();
        contentMap.put("taskId", taskId);
        contentMap.put("content", content);
        Long flyerId = hotportUavTaskDto.getFlyerId();

        //添加子任务
        String hotPortNumberList = hotportUavTaskDto.getHotPortNumberList();
        String countryCodeList = hotportUavTaskDto.getCountryCodeList();
        CommEventTaskTrack commEventTaskTrack = new CommEventTaskTrack().setHotPortNumber(
                hotPortNumberList).setCountryCode(countryCodeList).setTaskId(taskId).setForestkeeperId(flyerId);
        commEventTaskTrackDao.insert(commEventTaskTrack);

        // 记录消息中心
        fireCommandFeignClient.addBatch(new CommMsgCenterLogDTO(content, "2", new Date(), "1", userName, title,
                Stream.of(flyerId).collect(toList())));

        //消息推送
        List<String> flyerIdStr = Convert.convert(List.class, String.valueOf(flyerId));
        AliyunPushMessageUtils.customizeAdvancedPush(
                new AliPushMessagePojo(MsgConstants.TARGET_ACCOUNT, MsgConstants.PUSH_TYPE_MESSAGE,
                        MsgConstants.DEVICE_TYPE_ANDROID, title, flyerIdStr,
                        new AliPushContentPojo(NoticeTypeConstants.NOTICE_TYPE_CENTER_MSG,
                                JSON.toJSONString(contentMap))));
        return taskId;
    }

    @Override
    public Long addOtherTask(OtherTaskDto otherTaskDto) throws Exception {
        Long start = System.currentTimeMillis();
        log.info("开始下达普通任务:start:" + start);
        List<Long> recieverIdList = otherTaskDto.getRecieverIdList();
        if (recieverIdList == null && recieverIdList.size() <= 0) {
            throw new ForestBaseException("任务的接收人不能为空");
        }

        //插入数据库
        AppTask appTask = otherTaskDto.getAppTask();
        //获取用户ID
        Long userId = JwtTokenUtils.getId();
        appTask.setCreatePersonId(userId);
        baseMapper.insert(appTask);
        Long taskId = appTask.getId();
        Long first = System.currentTimeMillis();
        log.info("主任务表数据入库,耗时:" + (first - start));

        //格式化发送title和content
        String typeName = otherTaskDto.getTypeName();
        String title = formatMessage(messageFormatProperties.getTitleFormat(), typeName);
        //获取系统管理员姓名,从前端的jwt token中获取
        String userName = JwtTokenUtils.getRealName();
        String content = formatMessage(messageFormatProperties.getContentFormat(), userName, typeName);

        //添加子任务
        List<CommEventTaskTrack> commEventTaskTrackList = new ArrayList<>();
        for (Long recieverId : recieverIdList) {
            CommEventTaskTrack commEventTaskTrack = new CommEventTaskTrack();
            BeanUtil.copyProperties(otherTaskDto, commEventTaskTrack);
            commEventTaskTrack.setTaskId(taskId);
            commEventTaskTrack.setForestkeeperId(recieverId);
            // 添加指定任务详细地址
            commEventTaskTrack.setTaskDetailAddress(otherTaskDto.getDetailAddress());
            commEventTaskTrackList.add(commEventTaskTrack);
        }
        commEventTaskTrackDao.insertOtherTaskBatch(commEventTaskTrackList);

        Long second = System.currentTimeMillis();
        log.info("子任务表数据入库,耗时:" + (second - first));

        // 记录消息中心
        if (typeName.contains("巡护")) {
            //TODO 如果任务类型名称包含“巡护”,msgType=1
            CommMsgCenterLogDTO commMsgCenterLogDTO = new CommMsgCenterLogDTO(content, "1", new Date(), "1", userName,
                    title, recieverIdList);
            DataReturn dataReturn = fireCommandFeignClient.addBatch(commMsgCenterLogDTO);
            log.info("记录消息中心, {}", JSONUtil.toJsonStr(dataReturn));
        } else {
            // 如果任务类型名称不包含“巡护”,msgType=2 ，代表是巡航任务
            DataReturn dataReturn = fireCommandFeignClient.addBatch(
                    new CommMsgCenterLogDTO(content, "2", new Date(), "1", userName, title, recieverIdList));
            log.info("记录消息中心, {}", JSONUtil.toJsonStr(dataReturn));
        }
        Long third = System.currentTimeMillis();
        log.info("openfeign 调用消息中心,耗时:" + (third - second));

        Map<String, Object> contentMap = new HashMap<>();
        contentMap.put("taskId", taskId);
        contentMap.put("content", content);

        //阿里推送
        List<String> forestkeeperIdList = Convert.toList(String.class, recieverIdList);
        AliyunPushMessageUtils.customizeAdvancedPush(
                new AliPushMessagePojo(MsgConstants.TARGET_ACCOUNT, MsgConstants.PUSH_TYPE_MESSAGE,
                        MsgConstants.DEVICE_TYPE_ANDROID, title, forestkeeperIdList,
                        new AliPushContentPojo(NoticeTypeConstants.NOTICE_TYPE_CENTER_MSG,
                                JSON.toJSONString(contentMap))));
        //短信推送
        List<MicroSysUserAllInfoVo> microSysUserAllInfoVos = userInfoService.queryUserInfoByIds(recieverIdList);
        List<String> mobiles = microSysUserAllInfoVos.stream().map(MicroSysUserAllInfoVo::getMobile).filter(
                StrUtil::isNotEmpty).collect(Collectors.toList());
        SmsUtils.sendContent(mobiles, "SMS_465409670", new SmsAddTaskDto().setContent(typeName));

        Long forth = System.currentTimeMillis();
        log.info("消息推送,耗时:" + (forth - second));
        log.info("下达普通任务总耗时：" + (forth - start));
        return taskId;
    }

    @Override
    public void executeTask(ExecuteTaskDto executeTaskDto) {
        //修改主任务表状态
        String resultStatus = baseMapper.selectStatusById(executeTaskDto.getTaskId());
        String paramStatus = executeTaskDto.getStatus();
        if (!resultStatus.equals(paramStatus)) {
//            baseMapper.updateById(new AppTask().setStatus(paramStatus).setId(executeTaskDto.getTaskId()));
            baseMapper.update(new AppTask().setStartTime(executeTaskDto.getStartTime()).setStatus(paramStatus),
                    new QueryWrapper<AppTask>().eq("id", executeTaskDto.getTaskId()).isNull("start_time"));
        }
        //修改子任务表巡护类型和状态
        commEventTaskTrackDao.update(
                new CommEventTaskTrack().setTrackType(executeTaskDto.getTaskType()).setStatus(paramStatus),
                new QueryWrapper<CommEventTaskTrack>().eq("task_id", executeTaskDto.getTaskId()).eq("forestkeeper_id",
                        executeTaskDto.getForestkeeperId()));
    }

    @Override
    public void finishTask(FinishTaskDto finishTaskDto) {
        Date currentTime = new Date();
        //修改主任务表状态
        String status = finishTaskDto.getStatus();
        Long taskId = finishTaskDto.getTaskId();
        Long forestkeeperId = finishTaskDto.getForestkeeperId();
        List<Long> commEventTaskTrackIdList = commEventTaskTrackDao.selectIdByTaskIdAndStatus(taskId, status,
                forestkeeperId);
        if (CollectionUtils.isEmpty(commEventTaskTrackIdList)) {
            baseMapper.updateById(new AppTask().setStatus(status).setId(taskId).setFinishTime(currentTime));
        }
        //修改子任务表状态
        commEventTaskTrackDao.update(new CommEventTaskTrack().setStatus(status),
                new QueryWrapper<CommEventTaskTrack>().eq("task_id", taskId).eq("forestkeeper_id", forestkeeperId));
    }

    @Override
    public void normalTaskFinishTask(FinishTaskDto finishTaskDto) {
        Date currentTime = new Date();
        // 修改子任务表状态
        commEventTaskTrackDao.update(new CommEventTaskTrack().setStatus(finishTaskDto.getStatus()),
                new QueryWrapper<CommEventTaskTrack>().eq("task_id", finishTaskDto.getTaskId()).eq("forestkeeper_id",
                        finishTaskDto.getForestkeeperId()));

        // 修改主任务状态
        AppTask appTask = new AppTask();
        appTask.setStatus(finishTaskDto.getStatus());
        appTask.setId(finishTaskDto.getTaskId());
        appTask.setFinishTime(currentTime);
        appTask.setEndTime(currentTime);
        baseMapper.updateById(appTask);
    }

    @Override
    public int delete(Integer id) {
        return baseMapper.deleteById(id);
    }

    @Override
    public List<Integer> deleteBatch(Integer[] ids) {
        List<Integer> values = new ArrayList<Integer>();
        if (ids != null && ids.length > 0) {
            for (Integer id : ids) {
                values.add(delete(id));
            }
        }
        return values;
    }

    @Override
    public int updateData(AppTask appTask) {
        return baseMapper.updateById(appTask);
    }

    @Override
    public AppTask findById(Long id) {
        return baseMapper.selectRealParamsById(id);
    }

    @Override
    public IPage<AppTask> findListByPage(AppTask appTask, Integer page, Integer pageCount) {
        IPage<AppTask> appTaskPage = new Page<>(page, pageCount);
        QueryWrapper<AppTask> wrapper = new QueryWrapper<>();
        if (appTask != null) {
            if (StringUtils.hasText(appTask.getType())) {
                wrapper.eq("type", appTask.getType());
            }
            if (StringUtils.hasText(appTask.getStatus())) {
                wrapper.eq("status", appTask.getStatus());
            }
            if (StringUtils.hasText(appTask.getTitle())) {
                wrapper.eq("title", appTask.getTitle());
            }
            if (StringUtils.hasText(appTask.getContent())) {
                wrapper.eq("content", appTask.getContent());
            }
        }
        wrapper.orderByDesc("create_time");
        return baseMapper.selectPage(appTaskPage, wrapper);
    }

    @Override
    public List<AppTask> searchNoPage(AppTask appTask) {
        QueryWrapper<AppTask> wrapper = new QueryWrapper<>();
        if (appTask != null) {
            if (StringUtils.hasText(appTask.getType())) {
                wrapper.eq("type", appTask.getType());
            }
            if (StringUtils.hasText(appTask.getStatus())) {
                wrapper.eq("status", appTask.getStatus());
            }
            if (StringUtils.hasText(appTask.getTitle())) {
                wrapper.eq("title", appTask.getTitle());
            }
            if (StringUtils.hasText(appTask.getContent())) {
                wrapper.eq("content", appTask.getContent());
            }
        }
        wrapper.orderByDesc("create_time");
        return baseMapper.selectList(wrapper);
    }

    @Override
    public PageData<Object> searchTask(Integer taskType, Integer page, Integer rows) {
        IPage<AppTask> iPage = new Page<>(page, rows);
        IPage<AppTask> pages = appTaskDao.searchTaskByType(iPage, taskType);
        PageData<Object> pageData = new PageData<>();
        List<AppTask> records = pages.getRecords();
        //2022-05-19 优化 避免过度请求 -------fixed by yzx-------start
      /*  records.forEach(e -> {
            if (!"4".equals(e.getType()) && !"10".equals(e.getType())) {
                //非热点巡护
                Long taskId = e.getId();
                List<Long> executePersonId = appTaskDao.queryExecutePersonId(taskId);
                if (executePersonId != null && executePersonId.size() != 0) {
                    e.setExecutePersonId(executePersonId.get(0));
                    e.setExecutePersonName(getRealNameFromFeign(executePersonId.get(0)));
                }
            } else {
                //热点巡护
                Long taskId = e.getId();
                List<Long> executePersonId = appTaskDao.queryExecutePersonId(taskId);
                e.setExecutePersonName(executePersonId.size());
            }
        });*/
        final List<Long> ids = CollUtil.newArrayList();
        records.forEach(e -> {
            if (!"4".equals(e.getType()) && !"10".equals(e.getType())) {
                //非热点巡护
                Long taskId = e.getId();
                List<Long> executePersonId = appTaskDao.queryExecutePersonId(taskId);
                if (executePersonId != null && executePersonId.size() != 0) {
                    e.setExecutePersonId(executePersonId.get(0));
                    ids.add(e.getExecutePersonId());
                }
            } else {
                //热点巡护
                Long taskId = e.getId();
                List<Long> executePersonId = appTaskDao.queryExecutePersonId(taskId);
                e.setExecutePersonName(executePersonId.size());
            }
        });
        final Map<Long, String> idNameMapping = userInfoService.findAndConvertUserInfoByIds(ids);
        records.parallelStream()
                .filter(appTask ->
                        !StrUtil.equals("4", appTask.getType()) && !StrUtil.equals("10", appTask.getType())
                ).forEach(e -> {
            e.setExecutePersonName(ObjectUtil.defaultIfNull(idNameMapping.get(e.getExecutePersonId()), StrUtil.EMPTY));
        });
        //2022-05-19 优化 避免过度请求 -------fixed by yzx-------start
        pageData.setDatas(records);
        pageData.setCount((int) pages.getTotal());
        pageData.setCurrent((int) pages.getCurrent());
        pageData.setSize((int) pages.getSize());
        return pageData;
    }

    @Override
    public PageData<List<AppTask>> queryTotalTaskByCondition(Integer page, Integer rows,
                                                             AppTaskQueryDTO appTaskQueryDTO) {
        IPage<AppTask> iPage = new Page<>(page, rows);
        IPage<AppTask> pages = appTaskDao.queryTotalTaskByCondition(iPage, appTaskQueryDTO.getTaskType(),
                appTaskQueryDTO.getStartCreateTime(), appTaskQueryDTO.getEndCreateTime(), appTaskQueryDTO.getStatus()
                , appTaskQueryDTO.getStartExecuteTime(), appTaskQueryDTO.getEndExecuteTime(),
                appTaskQueryDTO.getForestkeeperIdList());
        List<AppTask> records = pages.getRecords();
        // 处理各种任务类型数据
        handleTaskList(records, appTaskQueryDTO.getTaskType(), appTaskQueryDTO.getStartExecuteTime(),
                appTaskQueryDTO.getEndExecuteTime());
        PageData<List<AppTask>> pageData = new PageData<>();
        pageData.setDatas(pages.getRecords());
        pageData.setCount((int) pages.getTotal());
        pageData.setCurrent((int) pages.getCurrent());
        pageData.setSize((int) pages.getSize());
        return pageData;
    }

    /**
     * //2022-05-19 优化 避免过度请求 -------fixed by yzx-------start
     * 处理任务集合
     */
    /*private void handleTaskList(List<AppTask> records, String taskType, String startExecuteTime, String endExecuteTime) {
        records.forEach(e -> {
            Long taskId = e.getId();
            Date endTime = e.getEndTime();
            String taskStatus = e.getStatus();
            String uavCode = null;
            List<Long> list = appTaskDao.queryTotalByExecuteTime(taskId, startExecuteTime, endExecuteTime);
            if (list != null && list.size() > 0) {
                if (!"4".equals(e.getType()) && !"10".equals(e.getType())) {
                    //非热点巡护
//                List<Long> executePersonId = appTaskDao.queryExecutePersonId(taskId);
//                if (executePersonId != null && executePersonId.size() != 0) {
                    e.setExecutePersonId(list.get(0));
                    List<String> personNameList = new ArrayList<>();
                    String executeName = getRealNameFromFeign(list.get(0));
                    if (StringUtils.hasText(executeName)) {
                        personNameList.add(executeName);
                    }
                    e.setExecutePersonName(personNameList);

                    String type = PatrolInfoUtil.getTaskType(taskType);
                    if ("cruise".equals(type)) {
                        //巡航任务 添加无人机名称
                        if ("2".equals(taskStatus)) {
                            //执行中
                            uavCode = appTaskDao.queryExecuteUavCode(list.get(0));
                        } else if ("3".equals(taskStatus)) {
                            //已完成
                            uavCode = appTaskDao.queryFinishUavCode(taskId, list.get(0));
                        }
                        e.setUavCode(uavCode);
                    }
//                }
                } else {
                    //热点巡护
                    if (list.size() == 1) {
                        e.setExecutePersonId(list.get(0));
                        List<String> personNameList = new ArrayList<>();
                        String executeName = getRealNameFromFeign(list.get(0));
                        if (StringUtils.hasText(executeName)) {
                            personNameList.add(executeName);
                        }
                        e.setExecutePersonName(personNameList);
                        //巡航任务 添加无人机名称
                        if ("2".equals(taskStatus)) {
                            //执行中
                            uavCode = appTaskDao.queryExecuteUavCode(list.get(0));
                        } else if ("3".equals(taskStatus)) {
                            //已完成
                            uavCode = appTaskDao.queryFinishUavCode(taskId, list.get(0));
                        }
                        e.setUavCode(uavCode);
                    } else {
                        e.setExecutePersonName(list);
                        if ("10".equals(taskType)) {
                            //巡航任务 添加无人机名称
                            e.setUavCode(list.size());
                        }
                    }
                }
            }
//            Date startTime = appTaskDao.queryStartExecuteTime(taskId, startExecuteTime, endExecuteTime);
//            e.setStartTime(startTime);
            if (e.getFinishTime() != null) {
                if (PatrolInfoUtil.isDelay(endTime, e.getFinishTime())) {
                    e.setIsDelay(1);
                } else {
                    e.setIsDelay(0);
                }
            } else if (PatrolInfoUtil.isDelay(endTime, new Date())) {
                e.setIsDelay(1);
            } else {
                e.setIsDelay(0);
            }
            e.setCreatePersonName(getRealNameFromFeign(e.getCreatePersonId()));

            String type = PatrolInfoUtil.getTaskType(taskType);
            if ("patrol".equals(type)) {
                //巡护
                Long pendingNumber = appPatrolTrackDao.querySubTaskNumber(taskId, "1");
                Long executingNumber = appPatrolTrackDao.querySubTaskNumber(taskId, "2");
                Long doneNumber = appPatrolTrackDao.querySubTaskNumber(taskId, "3");
                e.setPendingNumber(pendingNumber);
                e.setExecutingNumber(executingNumber);
                e.setDoneNumber(doneNumber);
                String time = null;
                if (endTime != null) {
                    time = TimeUtils.convertStringTime(endTime);
                }
                Long delayNumber = appPatrolTrackDao.queryDelayNumber(taskId, time);
                e.setDelayNumber(delayNumber);
            } else if ("cruise".equals(type)) {
                //巡航
                Object pendingNumber = uavFeignClient.querySubTaskNumber(taskId, "1").getData();
                Object executingNumber = uavFeignClient.querySubTaskNumber(taskId, "2").getData();
                Object doneNumber = uavFeignClient.querySubTaskNumber(taskId, "3").getData();
                e.setPendingNumber(pendingNumber);
                e.setExecutingNumber(executingNumber);
                e.setDoneNumber(doneNumber);
                Object delayNumber = uavFeignClient.queryDelayNumber(taskId, endTime).getData();
                e.setDelayNumber(delayNumber);
            }
        });
    }*/
    private void handleTaskList(List<AppTask> records, String taskType, String startExecuteTime,
                                String endExecuteTime) {
        final List<Long> ids = CollUtil.newArrayList();
        //记录当前 appTaskDao 查询
        final Map<Long, List<Long>> totalList = Maps.newHashMap();
        records.forEach(e -> {
            Long taskId = e.getId();
            Date endTime = e.getEndTime();
            String taskStatus = e.getStatus();
            String uavCode = null;
            List<Long> list = appTaskDao.queryTotalByExecuteTime(taskId, startExecuteTime, endExecuteTime);
            //记录此条结果集
            totalList.put(taskId, ObjectUtil.cloneByStream(list));
            if (list != null && list.size() > 0) {
                if (!"4".equals(e.getType()) && !"10".equals(e.getType())) {
                    e.setExecutePersonId(list.get(0));
                    ids.add(e.getExecutePersonId());
                    String type = PatrolInfoUtil.getTaskType(taskType);
                    if ("cruise".equals(type)) {
                        //巡航任务 添加无人机名称
                        if ("2".equals(taskStatus)) {
                            //执行中
                            uavCode = appTaskDao.queryExecuteUavCode(list.get(0));
                        } else if ("3".equals(taskStatus)) {
                            //已完成
                            uavCode = appTaskDao.queryFinishUavCode(taskId, list.get(0));
                        }
                        e.setUavCode(uavCode);
                    }
                } else {
                    //热点巡护
                    if (list.size() == 1) {
                        e.setExecutePersonId(list.get(0));
                        //巡航任务 添加无人机名称
                        if ("2".equals(taskStatus)) {
                            //执行中
                            uavCode = appTaskDao.queryExecuteUavCode(list.get(0));
                        } else if ("3".equals(taskStatus)) {
                            //已完成
                            uavCode = appTaskDao.queryFinishUavCode(taskId, list.get(0));
                        }
                        e.setUavCode(uavCode);
                    } else {
                        e.setExecutePersonName(list);
                        if ("10".equals(taskType)) {
                            //巡航任务 添加无人机名称
                            e.setUavCode(list.size());
                        }
                    }
                }
            }
            if (e.getFinishTime() != null) {
                if (PatrolInfoUtil.isDelay(endTime, e.getFinishTime())) {
                    e.setIsDelay(1);
                } else {
                    e.setIsDelay(0);
                }
            } else if (PatrolInfoUtil.isDelay(endTime, new Date())) {
                e.setIsDelay(1);
            } else {
                e.setIsDelay(0);
            }
            ids.add(e.getCreatePersonId());
            String type = PatrolInfoUtil.getTaskType(taskType);
            if ("patrol".equals(type)) {
                //巡护
                Long pendingNumber = appPatrolTrackDao.querySubTaskNumber(taskId, "1");
                Long executingNumber = appPatrolTrackDao.querySubTaskNumber(taskId, "2");
                Long doneNumber = appPatrolTrackDao.querySubTaskNumber(taskId, "3");
                e.setPendingNumber(pendingNumber);
                e.setExecutingNumber(executingNumber);
                e.setDoneNumber(doneNumber);
                String time = null;
                if (endTime != null) {
                    time = TimeUtils.convertStringTime(endTime);
                }
                Long delayNumber = appPatrolTrackDao.queryDelayNumber(taskId, time);
                e.setDelayNumber(delayNumber);
            } else if ("cruise".equals(type)) {
                //巡航
                Object pendingNumber = uavFeignClient.querySubTaskNumber(taskId, "1").getData();
                Object executingNumber = uavFeignClient.querySubTaskNumber(taskId, "2").getData();
                Object doneNumber = uavFeignClient.querySubTaskNumber(taskId, "3").getData();
                e.setPendingNumber(pendingNumber);
                e.setExecutingNumber(executingNumber);
                e.setDoneNumber(doneNumber);
                Object delayNumber = uavFeignClient.queryDelayNumber(taskId, endTime).getData();
                e.setDelayNumber(delayNumber);
            }
        });
        //20220602 补充 start
        //不用去重，查询自动去重 findAndConvertUserInfoByIds
        ids.addAll(totalList.values().stream()
                .flatMap(Collection::stream)
                .collect(Collectors.toList()));
        //20220602 补充 end

        //处理用户名称
        com.telit.common.core.utils.Result<Map<Long, MicroSysUserVo>> selectByBatchIdsResult = remoteUpmsService.selectByBatchIds(
                ids, true);
        Map<Long, MicroSysUserVo> microSysUserVoMap = FeignUtils.unwrap(selectByBatchIdsResult);

        records.forEach(e -> {
            e.setCreatePersonName(microSysUserVoMap.get(e.getCreatePersonId()) != null ? microSysUserVoMap.get(
                    e.getCreatePersonId()).getRealName() : "");
            final List<Long> previousList = totalList.get(e.getId());
            if (CollUtil.isNotEmpty(previousList)) {
                if (!"4".equals(e.getType()) && !"10".equals(e.getType())) {
                    final String personName =
                            microSysUserVoMap.get(e.getExecutePersonId()) != null ? microSysUserVoMap.get(
                                    e.getExecutePersonId()).getRealName() : "";
                    final List<String> person = CollUtil.newArrayList();
                    if (!StrUtil.isEmpty(personName)) {
                        person.add(personName);
                    }
                    e.setExecutePersonName(person);
                } else {
                    if (previousList.size() == 1) {
                        final String personName =
                                microSysUserVoMap.get(e.getExecutePersonId()) != null ? microSysUserVoMap.get(
                                        e.getExecutePersonId()).getRealName() : "";
                        final List<String> person = CollUtil.newArrayList();
                        if (!StrUtil.isEmpty(personName)) {
                            person.add(personName);
                        }
                        e.setExecutePersonName(person);
                    }
                }
            }
        });
    }

    @Override
    public PageData<Object> queryTaskDetailByTaskId(Integer page, Integer rows, Long taskId) {
        IPage<AppPatrolTrack> iPage = new Page<>(page, rows);
        IPage<AppPatrolTrack> pages = appPatrolTrackDao.queryTaskDetailByTaskId(iPage, taskId);
        List<AppPatrolTrack> records = pages.getRecords();
        Date endTime = appTaskDao.queryEndTime(taskId);
        //2022-05-19 优化 避免过度请求 -------fixed by yzx-------start

        /*records.forEach(e -> {
            if (PatrolInfoUtil.isDelay(endTime, e.getEndTime())) {
                e.setIsDelay(1); //0未预期 1已预期
            } else {
                e.setIsDelay(0);
            }
            e.setProtectorName(getRealNameFromFeign(e.getProtectorId()));
            // 转换距离km
            e.setDistance(HandleStrUtils.handlerDistanceToKm(e.getDistance()));
            // 转换时长
            e.setDuration(TimeUtils.secondsToFormat(e.getDuration()));
        });*/
        final List<Long> ids = records.stream().map(AppPatrolTrack::getProtectorId).collect(Collectors.toList());
        final Map<Long, String> idNameMapping = userInfoService.findAndConvertUserInfoByIds(ids);
        records.forEach(e -> {
            if (PatrolInfoUtil.isDelay(endTime, e.getEndTime())) {
                e.setIsDelay(1); //0未预期 1已预期
            } else {
                e.setIsDelay(0);
            }
            e.setProtectorName(ObjectUtil.defaultIfNull(idNameMapping.get(e.getProtectorId()), StrUtil.EMPTY));
            // 转换距离km
            e.setDistance(HandleStrUtils.handlerDistanceToKm(e.getDistance()));
            // 转换时长
//            e.setDuration(TimeUtils.secondsToFormat(e.getDuration()));
            //根据安卓端要求对时长做保留一位小数的要求，单位是分钟
            e.setDuration(StrUtil.isNotEmpty(e.getDuration()) ?
                    NumberUtil.div(NumberUtil.toBigDecimal(e.getDuration()), NumberUtil.toBigDecimal("60"),
                            1).toPlainString() : "0");
        });
        //2022-05-19 优化 避免过度请求 -------fixed by yzx-------end
        PageData<Object> pageData = new PageData<>();
        pageData.setDatas(records);
        pageData.setCount((int) pages.getTotal());
        pageData.setCurrent((int) pages.getCurrent());
        pageData.setSize((int) pages.getSize());
        return pageData;
    }

    @Override
    public List<AppTrackDTO> listCruiseTaskByUserId(PatrolTaskQueryDTO patrolTaskQueryDTO) {
        List<String> statusList = null;
        if (StringUtils.hasText(patrolTaskQueryDTO.getTaskStatus())) {
            statusList = Arrays.asList(patrolTaskQueryDTO.getTaskStatus().split(","));
        }

        List<AppTrackDTO> list = commEventTaskTrackDao.cruiseTaskListByUserId(patrolTaskQueryDTO, statusList);
        // 参数处理
        paramDistanceAndDuration(list);
//        list.forEach(e->{
//            Long taskId = e.getTaskId();
//            Long forestkeeperId = e.getForestkeeperId();
//            this.setTaskLongitudeAndLatitude(e,forestkeeperId,taskId);
//        });
        return list;
    }

    @Override
    public PageData<Object> listCruiseTaskByPage(Integer current, Integer size, PatrolTaskQueryDTO patrolTaskQueryDTO) {
        IPage<AppTrackDTO> iPage = listCruiseTaskByUserIdPage(current, size, patrolTaskQueryDTO);
        List<AppTrackDTO> list = paramDistanceAndDuration(iPage.getRecords());
        return new PageData<>((int) iPage.getTotal(), current, size, list);
    }


    /**
     * 巡航任务分页数据
     *
     * @param current
     * @param size
     * @param patrolTaskQueryDTO
     *
     * @return
     */
    public IPage<AppTrackDTO> listCruiseTaskByUserIdPage(Integer current, Integer size,
                                                         PatrolTaskQueryDTO patrolTaskQueryDTO) {
        IPage<AppTrackDTO> iPage = new Page<>(current, size);
        List<String> statusList = null;
        if (StringUtils.hasText(patrolTaskQueryDTO.getTaskStatus())) {
            statusList = Arrays.asList(patrolTaskQueryDTO.getTaskStatus().split(","));
        }
        return commEventTaskTrackDao.cruiseTaskListByUserIdPage(iPage, patrolTaskQueryDTO, statusList);
    }

    /**
     * 巡护任务分页数据
     *
     * @param current
     * @param size
     * @param patrolTaskQueryDTO
     *
     * @return
     */
    public IPage<AppTrackDTO> listPatrolTaskByUserPage(Integer current, Integer size,
                                                       PatrolTaskQueryDTO patrolTaskQueryDTO) {
        IPage<AppTrackDTO> iPage = new Page<>(current, size);
        List<String> statusList = null;
        if (StringUtils.hasText(patrolTaskQueryDTO.getTaskStatus())) {
            statusList = Arrays.asList(patrolTaskQueryDTO.getTaskStatus().split(","));
        }
        return commEventTaskTrackDao.patrolTaskListByUserIdPage(iPage, patrolTaskQueryDTO, statusList);
    }

    @Override
    public List<AppTrackDTO> listPatrolTaskByUserId(PatrolTaskQueryDTO dto) {
        List<String> statusList = null;
        if (StringUtils.hasText(dto.getTaskStatus())) {
            statusList = Arrays.asList(dto.getTaskStatus().split(","));
        }

        List<AppTrackDTO> list = commEventTaskTrackDao.patrolTaskListByUserId(dto, statusList);
        // 参数处理
        paramDistanceAndDuration(list);
        return list;
    }

    @Override
    public PageData<Object> listPatrolTaskByPage(Integer current, Integer size, PatrolTaskQueryDTO patrolTaskQueryDTO) {
        IPage<AppTrackDTO> iPage = listPatrolTaskByUserPage(current, size, patrolTaskQueryDTO);
        List<AppTrackDTO> list = paramDistanceAndDuration(iPage.getRecords());
        return new PageData<>((int) iPage.getTotal(), current, size, list);
    }


    @Override
    public AppTrackDTO patrolDetailById(Long userId, Long id) {
        AppTrackDTO appTrackDTO = commEventTaskTrackDao.patrolTaskById(userId, id);
        if (appTrackDTO == null || appTrackDTO.getStatus() == null) {
            return appTrackDTO;
        }
        //转换停留时间从秒到分钟，保留一位小数
        final String pauseDuration = StrUtil.isNotEmpty(appTrackDTO.getPauseDuration()) ?
                NumberUtil.div(NumberUtil.toBigDecimal(appTrackDTO.getPauseDuration()), NumberUtil.toBigDecimal("60"),
                        1).toPlainString() : "0";

        //转换巡护/巡航时长，从秒到分钟，并保留一位小数
        final String duration = StrUtil.isNotEmpty(appTrackDTO.getDuration()) ?
                NumberUtil.div(NumberUtil.toBigDecimal(appTrackDTO.getDuration()), NumberUtil.toBigDecimal("60"),
                        1).toPlainString() : "0";
        appTrackDTO.setDuration(duration);

        // 设置下发人
        taskDetailBaseStep(appTrackDTO);

        //封装多媒体全路径
      /*  if(!StringUtils.isEmpty(appTrackDTO.getMediaUrl())) {
            List<String> imageUrlList = JSON.parseArray(appTrackDTO.getMediaUrl(), String.class);
            ArrayList<String> fullImageUrlList=new ArrayList<>();
            for(String imageUrl :imageUrlList) {
                String fullMediaUrl = MinioUtils.previewImg(imageUrl);
                fullImageUrlList.add(fullMediaUrl);
            }
            appTrackDTO.setMediaUrl(JSON.toJSONString(fullImageUrlList));
        }*/

        // 如果是热点任务,查询任务各种状态的人数
        if ("4".equals(appTrackDTO.getTaskType())) {
            List<AppTrackDTO> list = commEventTaskTrackDao.selectPatrolStatusAndEndTimeByTaskId(
                    appTrackDTO.getTaskId());
            setTaskStatusCount(list, appTrackDTO);

            // 设置热点面积
//            if (appTrackDTO.getHotTime() != null && StringUtils.hasText(appTrackDTO.getHotPortNumber())) {
//                setArea(appTrackDTO);
//            }

        }

        // 设置详细信息
        setDetailAddress(appTrackDTO);

        //设置任务经纬度
        setTaskLongitudeAndLatitude(appTrackDTO, userId, id);

        // 如果状态为1(待执行),直接返回数据
        if ("1".equals(appTrackDTO.getStatus())) {
            return appTrackDTO;
        }

        // 封装反馈基本信息
//        simpleTaskDetailFeedback(appTrackDTO);
        //根据产品需求，反馈信息有多条
        taskDetailFeedbacks(appTrackDTO, userId, id);

        // 封装时长，距离，点位集合
        PatrolInfoUtil.setDistantAndDurationAndPointCollection(appTrackDTO, userId, id);

//        // 封装查询轨迹点集合
//        String pointCollection = getPointCollection(userId, id);
//        preparePointCollection(pointCollection,appTrackDTO);

        appTrackDTO.setPauseDuration(pauseDuration);
        return appTrackDTO;
    }

    @Override
    public List<AppTask> queryTaskByUavCode(String uavCode) {
        return appTaskDao.queryTaskByUavCode(uavCode);
    }

    @Override
    public AppTrackDTO cruiseTaskDetailById(Long userId, Long id) {
        AppTrackDTO appTrackDTO = commEventTaskTrackDao.cruiseTaskById(userId, id);
        if (appTrackDTO == null || appTrackDTO.getStatus() == null) {
            return appTrackDTO;
        }

        //TODO此操作为应对南京浦口防火进行的暂时性操作，后期整个方法需要优化掉
        if (StrUtil.equals(appTrackDTO.getEquipmentModel(), "10018")) {
            appTrackDTO.setEquipmentModel("经纬M300RTK");
        }
        //取任务结束时间-开始时间作为区间/60转成分钟
        String duration = StrUtil.isNotEmpty(appTrackDTO.getDuration()) ?
                NumberUtil.div(NumberUtil.toBigDecimal(appTrackDTO.getDuration()), NumberUtil.toBigDecimal("60"),
                        1).toPlainString() : "0";
        appTrackDTO.setDuration(duration);

        //封装多媒体全路径
       /* if(!StringUtils.isEmpty(appTrackDTO.getMediaUrl())) {
            List<String> imageUrlList = JSON.parseArray(appTrackDTO.getMediaUrl(), String.class);
            ArrayList<String> fullImageUrlList=new ArrayList<>();
            for(String imageUrl :imageUrlList) {
                String fullMediaUrl = MinioUtils.previewImg(imageUrl);
                fullImageUrlList.add(fullMediaUrl);
            }
            appTrackDTO.setMediaUrl(JSON.toJSONString(fullImageUrlList));
        }*/

        MicroSysUserAllInfoVo sysUserDetailVo = userInfoService.getUserInfo(userId);
        appTrackDTO.setForestkeeper(sysUserDetailVo == null ? null : sysUserDetailVo.getRealName());
        // 设置下发人
        taskDetailBaseStep(appTrackDTO);

        // 如果是热点巡航任务,查询任务各种状态的人数
        if ("10".equals(appTrackDTO.getTaskType())) {
            List<AppTrackDTO> list = commEventTaskTrackDao.selectCruiseStatusAndEndTimeByTaskId(
                    appTrackDTO.getTaskId());
            setTaskStatusCount(list, appTrackDTO);

            // 设置热点面积
            if (appTrackDTO.getHotTime() != null && StringUtils.hasText(appTrackDTO.getHotPortNumber())) {
                setArea(appTrackDTO);
            }
        }
        //设置任务经纬度
        setTaskLongitudeAndLatitude(appTrackDTO, userId, id);

        // 设置详细信息
        setDetailAddress(appTrackDTO);

        // 如果状态为1(待执行),直接返回数据
        if ("1".equals(appTrackDTO.getStatus())) {
            return appTrackDTO;
        }

        // 当前任务再执行中，没有轨迹,从无人机飞行详情中查询
        if (StringUtils.isEmpty(appTrackDTO.getUavCode())) {
            AppUavTrackDetail appUavTrackDetail = getUavInfoFromFlyDetail(userId, id);
            if (appUavTrackDetail != null) {
                appTrackDTO.setUavCode(appUavTrackDetail.getUavCode());
                appTrackDTO.setUavName(appUavTrackDetail.getUavName());
            }
        }

        // 封装反馈基本信息
        simpleTaskDetailFeedback(appTrackDTO);

        // 封装时长，距离，点位集合
        PatrolInfoUtil.setDistantAndDurationAndPointCollection(appTrackDTO, userId, id);

//        // 封装实时轨迹点
//        String pointCollection = getPointCollection(userId, id);
//        preparePointCollection(pointCollection,appTrackDTO);

        return appTrackDTO;
    }

    /**
     * 设置任务所在经纬度
     *
     * @param appTrackDTO
     * @param userId
     * @param taskId
     */
    private void setTaskLongitudeAndLatitude(AppTrackDTO appTrackDTO, Long userId, Long taskId) {
        LongitudeAndLatitudeDTO dto = null;
        if ("2".equals(appTrackDTO.getTaskType()) || "8".equals(appTrackDTO.getTaskType())) {
            //指定巡护查询子任务表
            dto = commEventTaskTrackDao.queryLongitudeAndLatitude(userId, taskId);
        } else if ("1".equals(appTrackDTO.getTaskType()) || "7".equals(appTrackDTO.getTaskType())) {
            //日常巡护任务没有经纬度
            return;
        } else {
            //非指定巡护查询火情表
            if (appTrackDTO.getEventId() != null) {
                DataReturn dataReturn = fireCommandFeignClient.queryLongitudeAndLatitude(
                        appTrackDTO.getEventId().toString());
                if (dataReturn != null && dataReturn.getData() != null && dataReturn.getCode().equals(
                        ResultCode.SUCCESS.getCode())) {
                    dto = JSON.parseObject(JSON.toJSONString(dataReturn.getData()), LongitudeAndLatitudeDTO.class);
                }
            }
        }
        if (dto != null) {
            appTrackDTO.setTaskLongitude(dto.getLongitude());
            appTrackDTO.setTaskLatitude(dto.getLatitude());
        }

    }

    @Override
    public List<AppTrackDTO> listUavTaskByUavCode(String uavCode) {
        //20220419 尝试优化，避免一个接口几百次查db
        final List<AppTrackDTO> list = commEventTaskTrackDao.uavTaskListByCode(uavCode, "2");
        //求出所有id
        final List<Long> forestKeeperIds = list.parallelStream().map(AppTrackDTO::getForestkeeperId).distinct().collect(
                Collectors.toList());
        final Map<Long, String> nameMap = Maps.newHashMap();
        if (CollUtil.isNotEmpty(forestKeeperIds)) {
            final List<MicroSysUserAllInfoVo> vos = userInfoService.queryUserInfoByIds(forestKeeperIds);
            if (CollUtil.isNotEmpty(vos)) {
                nameMap.putAll(vos.stream().collect(
                        Collectors.toMap(MicroSysUserAllInfoVo::getId, MicroSysUserAllInfoVo::getRealName)));
            }
        }

        list.forEach(ptd -> {
            ptd.setDistance(HandleStrUtils.handlerDistanceToKm(ptd.getDistance()));
            ptd.setDuration(TimeUtils.secondsToFormat(ptd.getDuration()));
            ptd.setForestkeeper(nameMap.get(ptd.getForestkeeperId()));
        });


            /* 几百次的db方法暂时不用。浪费系统资源
        list.forEach(patrolTaskDTO -> {
            patrolTaskDTO.setDistance(HandleStrUtils.handlerDistanceToKm(patrolTaskDTO.getDistance()));
            patrolTaskDTO.setDuration(TimeUtils.secondsToFormat(patrolTaskDTO.getDuration()));
            //patrolTaskDTO.setForestkeeper(getRealNameFromFeign(patrolTaskDTO.getForestkeeperId()));
        });*/

        return list;
    }


    @Override
    public void startExecuteTask(Long subTaskId, HttpServletRequest httpServletRequest) {
        //查询该子任务对应的主任务状态，如果主任务状态为待执行，修改为执行中
        String status = appTaskDao.queryStatus(subTaskId);
        if ("1".equals(status)) {
            appTaskDao.changeStatus(subTaskId, "2");
        }
        //修改子任务表的任务状态
        appTaskDao.changeSubTaskStatus(subTaskId, "2");
    }

    @Override
    public void finishExecuteTask(Long subTaskId, HttpServletRequest httpServletRequest) {
        //修改子任务状态
        appTaskDao.changeSubTaskStatus(subTaskId, "3");
        //查询所有子任务状态，如果除了当前子任务的其他子任务都已完成，则将主任务设置为已完成
        List<Long> list = appTaskDao.queryNotFinishSubTaskWithoutSelf(subTaskId);
        if (list.size() == 0) {
            appTaskDao.changeFinishTime(subTaskId, new Date(), "3");
        }
    }

    @Override
    public AppTrackDTO unFinishPatrolDetailById(Long userId, Long id) {
        AppTrackDTO appTrackDTO = commEventTaskTrackDao.patrolTaskById(userId, id);
        if (appTrackDTO == null) {
            return null;
        }
        // 处理参数
        String mediaUrl = appTrackDTO.getMediaUrl();
        appTrackDTO.setMediaList(MediaUrlUtils.handleMediaUrlToList(mediaUrl));
        appTrackDTO.setCreatePersonName(getRealNameFromFeign(appTrackDTO.getCreatePersonId()));
        // 设置行政区划名称以及详细地址
        setDetailAddress(appTrackDTO);

        // 如果是热点任务查询热点面积,根据村code和热点编号查询
        if (("4".equals(appTrackDTO.getTaskType()) || "10".equals(appTrackDTO.getTaskType()))
                && appTrackDTO.getHotTime() != null && StringUtils.hasText(appTrackDTO.getHotPortNumber())) {
            setArea(appTrackDTO);
        }

        return appTrackDTO;
    }

    @Override
    public Long startNormalTask(NormalTaskDTO normalTaskDTO) {
        // 添加app_task主任务表数据
        AppTask appTask = new AppTask();
        appTask.setCreatePersonId(normalTaskDTO.getForestkeeperId());
        //日常任务把开始执行时间作为任务下达时间
        Date startTime = normalTaskDTO.getStartTime();
        appTask.setCreateTime(normalTaskDTO.getStartTime());
        appTask.setStatus(normalTaskDTO.getStatus()); // 日常任务一开始就是执行中2
        appTask.setType(normalTaskDTO.getType());
        appTask.setStartTime(startTime);
        // 设置默认标题
        if (StringUtils.isEmpty(normalTaskDTO.getTitle())) {
            // 查询日常巡护/巡航次数
            int normalNum = commEventTaskTrackDao.selectNormalTaskCount(normalTaskDTO.getForestkeeperId(),
                    normalTaskDTO.getType());
            if ("1".equals(normalTaskDTO.getType())) {
                appTask.setTitle(
                        TaskMsgConstants.getTitleNormal(TaskMsgConstants.TASK_TITLE_PATROL_NORMAL_TEMPLATE, startTime,
                                normalTaskDTO.getForesterName(), normalNum + 1));
            } else if ("7".equals(normalTaskDTO.getType())) {
                appTask.setTitle(
                        TaskMsgConstants.getTitleNormal(TaskMsgConstants.TASK_TITLE_CRUISE_NORMAL_TEMPLATE, startTime,
                                normalTaskDTO.getForesterName(), normalNum + 1));
            }
        }

        // 设置默认内容
        if (StringUtils.isEmpty(normalTaskDTO.getContent())) {
            if ("1".equals(normalTaskDTO.getType())) {
                appTask.setContent(TaskMsgConstants.TASK_CONTENT_PATROL__NORMAL_TEMPLATE);
            } else if ("7".equals(normalTaskDTO.getType())) {
                appTask.setContent(TaskMsgConstants.TASK_CONTENT_CRUISE_NORMAL_TEMPLATE);
            }
        }
        baseMapper.insert(appTask);
        Long taskId = appTask.getId();

        // 添加子任务表数据
        CommEventTaskTrack commEventTaskTrack = new CommEventTaskTrack(normalTaskDTO, taskId);
        commEventTaskTrackDao.insert(commEventTaskTrack);
        return taskId;
    }

    /**
     * 准备实时轨迹点
     */
    private void preparePointCollection(String pointCollection, AppTrackDTO appTrackDTO) {
        if (StringUtils.hasText(pointCollection)) {
            Object[] objects = JSON.parseArray(pointCollection).toArray();
            Object object = objects[objects.length - 1];
            if (object != null) {
                JSONArray str = (JSONArray) object;
                appTrackDTO.setLongitude(String.valueOf(str.get(0)));
                appTrackDTO.setLatitude(String.valueOf(str.get(1)));
            }
        }
        appTrackDTO.setPointCollection(pointCollection);
    }

    /**
     * 任务详情第一步封装数据
     *
     * @param appTrackDTO
     */
    private void taskDetailBaseStep(AppTrackDTO appTrackDTO) {
        // 设值-下发人
        appTrackDTO.setCreatePersonName(getRealNameFromFeign(appTrackDTO.getCreatePersonId()));
        // 设置-执行人
        appTrackDTO.setForestkeeper(getRealNameFromFeign(appTrackDTO.getForestkeeperId()));
        // 是否逾期
        if (PatrolInfoUtil.isDelay(appTrackDTO.getEndTime(), appTrackDTO.getTaskEndTime())) {
            appTrackDTO.setIsDelay(1);
        } else {
            appTrackDTO.setIsDelay(0);
        }

    }

    /**
     * 设置详细地址数据
     *
     * @param appTrackDTO
     */
    private void setDetailAddress(AppTrackDTO appTrackDTO) {
        // 设置详细地址
        // 若是1火情类型任务查询火情表
        String detailAddress = StringUtil.EMPTY;
        if ("1".equals(appTrackDTO.getEventType())) {
            DataReturn dataReturn = fireCommandFeignClient.queryAddressById(appTrackDTO.getEventId().toString());
            if (dataReturn != null && dataReturn.getData() != null) {
                SimpleFireAlarmDTO commFireAlarm = JSON.parseObject(JSON.toJSONString(dataReturn.getData()),
                        SimpleFireAlarmDTO.class);
                detailAddress = commFireAlarm.getDetailAddress();
                appTrackDTO.setDistrictName(commFireAlarm.getDistrictName());
            }

        } else if ("2".equals(appTrackDTO.getEventType())) {
            DataReturn dataReturn = fireCommandFeignClient.detail(appTrackDTO.getEventId().toString());
            if (dataReturn != null && dataReturn.getData() != null) {
                CommEventDTO commEvent = JSON.parseObject(JSON.toJSONString(dataReturn.getData()), CommEventDTO.class);
                detailAddress = commEvent.getDetailAddress();
                appTrackDTO.setDistrictName(commEvent.getDistrictName());
            }
        } else if ("3".equals(appTrackDTO.getEventType())) {
            // 地址从新增字段中获取
            detailAddress = appTrackDTO.getTaskDetailAddress();
            // 地址字段为空,指定巡护/巡航,根据模板进行地址截取
            if (StringUtils.isEmpty(detailAddress)) {
                String content = appTrackDTO.getContent();
                String strStart = "前往【";
                if (StringUtils.hasText(content) && content.contains(strStart)) {
                    int strStartIndex = content.indexOf(strStart);
                    int strEndIndex = content.indexOf("】【");
                    detailAddress = content.substring(strStartIndex, strEndIndex).substring(strStart.length());
                }
            }
        } else if ("4".equals(appTrackDTO.getTaskType()) || "10".equals(appTrackDTO.getTaskType())) {
            detailAddress = appTrackDTO.getHotAddress();
        }
        appTrackDTO.setDetailAddress(detailAddress);
    }

    /**
     * 对于一个用户一个任务多条反馈消息的设计
     * 准备任务反馈数据
     *
     * @param appTrackDTO
     * @param userId
     * @param id
     */
    private void mulitTaskDetailFeedback(AppTrackDTO appTrackDTO, Long userId, Long id) {
        // 处理参数
        String mediaUrl = appTrackDTO.getMediaUrl();
        appTrackDTO.setMediaList(MediaUrlUtils.handleMediaUrlToList(mediaUrl));

        // 封装反馈列表，考虑到多次反馈
        List<AppTaskFeedback> feedbackList = commEventTaskTrackDao.selectFeedbackByUserIdAndTaskId(userId, id);
        if (!CollectionUtils.isEmpty(feedbackList)) {
            feedbackList.forEach(
                    feedback -> feedback.setMediaList(MediaUrlUtils.handleMediaUrlToList(feedback.getMediaUrl())));
        }
        appTrackDTO.setTaskFeedBackList(feedbackList);
    }

    /**
     * 对于一个用户一个任务一条反馈记录的设计
     *
     * @param appTrackDTO
     */
    private void simpleTaskDetailFeedback(AppTrackDTO appTrackDTO) {
        List<AppTaskFeedback> list = new ArrayList<>();
        AppTaskFeedback appTaskFeedback = new AppTaskFeedback();
        if (!StringUtils.isEmpty(appTrackDTO.getMediaUrl())) {
            List<String> mediaUrlList = JSON.parseArray(appTrackDTO.getMediaUrl(), String.class);
            List<String> fullMediaUrlList = new ArrayList<>();
            for (String mediaUrl : mediaUrlList) {
                //TODO:v1.1.0
//                String fullMediaUrl = MinioUtils.previewImg(mediaUrl);
//                fullMediaUrlList.add(fullMediaUrl);
            }
            appTaskFeedback.setMediaList(fullMediaUrlList);// 多媒体url
            appTaskFeedback.setMediaUrl(JSON.toJSONString(fullMediaUrlList));
            appTrackDTO.setMediaUrl(JSON.toJSONString(fullMediaUrlList));
        }
        appTaskFeedback.setContent(appTrackDTO.getFeedbackContent()); // 反馈内容
        appTaskFeedback.setFeedbackTime(appTrackDTO.getFeedbackTime()); // 反馈时间
        appTaskFeedback.setFireType(appTrackDTO.getFireType()); // 火情类型
        list.add(appTaskFeedback);
        appTrackDTO.setTaskFeedBackList(list);
    }

    /**
     * 多条反馈记录
     */
    private void taskDetailFeedbacks(AppTrackDTO appTrackDTO, Long userId, Long id) {
        List<AppTaskFeedback> appTaskFeedbackList = appTaskDao.queryFeedbackById(id, userId);
        appTaskFeedbackList.forEach(e -> {
            if (!StringUtils.isEmpty(e.getMediaUrl())) {
                //处理多媒体
                List<String> mediaUrlList = JSON.parseArray(e.getMediaUrl(), String.class);
                List<String> imgList = new ArrayList<>();
                List<String> videoList = new ArrayList<>();
                List<String> audioList = new ArrayList<>();
                mediaUrlList.forEach(fileUrl -> {
                    String fileType = fileUrl.substring(fileUrl.lastIndexOf(".") + 1, fileUrl.length());
                    if (FILE_TYPE_IMAGE_LIST.contains(fileType) || fileType.length() > 10) {
                        imgList.add(fileUrl);
                    } else if (FILE_TYPE_VIDEO_LIST.contains(fileType)) {
                        videoList.add(fileUrl);
                    } else if (FILE_TYPE_AUDIO_LIST.contains(fileType)) {
                        audioList.add(fileUrl);
                    } else {
                    }
                });
                e.setMediaList(mediaUrlList);
                e.setImgList(imgList);
                e.setVideoList(videoList);
                e.setAudioList(audioList);
            }
        });
        appTrackDTO.setTaskFeedBackList(appTaskFeedbackList);
    }

    /**
     * 设置面积
     *
     * @param appTrackDTO
     */
    private void setArea(AppTrackDTO appTrackDTO) {
        Date hotTime = appTrackDTO.getHotTime();
        Date currentTime = new Date();
        int dayFlag = 0;
        //判断热点时间和当前时间差多少天
        long betweenDay = DateUtil.betweenDay(hotTime, currentTime, true);
        if (betweenDay == 0 || hotTime.getTime() - currentTime.getTime() < 0) {
            dayFlag = 1;
        } else if (hotTime.getTime() - currentTime.getTime() >= 0 && betweenDay == 1) {
            dayFlag = 2;
        } else {
            dayFlag = 3;
        }

        //获取String类型的时间
        String hotTimeStr = new SimpleDateFormat("yyyyMMdd").format(hotTime);
        // todo 查询热点面积是否根据行政区划查询
        String districtCode = null;
//        districtCode = JwtTokenUtils.getDistrictCode();
        DataReturn dataReturn = thirdFeignClient.selectMjByYjidAndCun(dayFlag, districtCode,
                appTrackDTO.getHotPortNumber(), hotTimeStr);
        if (dataReturn != null && dataReturn.getCode().equals(ResultCode.SUCCESS.getCode())) {
            if (dataReturn.getData() != null) {
                List<GeoPkFdiRdAreaDto> dtoList = JSON.parseArray(JSON.toJSONString(dataReturn.getData()),
                        GeoPkFdiRdAreaDto.class);
                BigDecimal area = new BigDecimal("0");
                if (!CollectionUtils.isEmpty(dtoList)) {
                    for (GeoPkFdiRdAreaDto geo : dtoList) {
                        area = new BigDecimal(geo.getMj()).add(area);
                    }
                    // 设置面积
                    NumberFormat nf = NumberFormat.getNumberInstance();
                    nf.setMaximumFractionDigits(3);
                    appTrackDTO.setHotArea(nf.format(area));
                }
            }
        }
    }

    /**
     * 任务执行人数
     */
    private void setTaskStatusCount(List<AppTrackDTO> list, AppTrackDTO appTrackDTO) {
        if (!CollectionUtils.isEmpty(list)) {
            int finishCount = 0; // 完成数量
            int executeCount = 0; // 执行中数量
            int unExecuteCount = 0; // 待执行数量
            int delayCount = 0; // 逾期任务数量
            int totalTaskCount = list.size();// 设置总任务的个数
            for (AppTrackDTO trackDTO : list) {
                String status = trackDTO.getStatus();
                if ("1".equals(status)) {
                    unExecuteCount++;
                } else if ("2".equals(status)) {
                    executeCount++;
                } else if ("3".equals(status)) {
                    finishCount++;
                }

                // 设置逾期的个数
                if (trackDTO.getTaskEndTime() != null && trackDTO.getFinishTime().before(trackDTO.getTaskEndTime())
                        || (trackDTO.getTaskEndTime() != null && trackDTO.getFinishTime() == null
                        && trackDTO.getTaskEndTime().before(new Date()))) {
                    delayCount++;
                }

            }
            appTrackDTO.setFinishCount(finishCount);
            appTrackDTO.setExecuteCount(executeCount);
            appTrackDTO.setUnExecuteCount(unExecuteCount);
            appTrackDTO.setDelayCount(delayCount);
            appTrackDTO.setTotalTaskCount(totalTaskCount);
        }
    }

    @Override
    public FireTaskNumberDTO queryPatrolTaskNumByFireId(Long fireId) {
        FireTaskNumberDTO fireTaskNumberDTO = new FireTaskNumberDTO();
        Integer patrolPendingExecuteNumber = appTaskDao.queryPatrolPendingExecuteNumber(fireId);
        Integer patrolUnderExecuteNumber = appTaskDao.queryPatrolUnderExecuteNumber(fireId);
        Integer patrolHasFinishedeNumber = appTaskDao.queryPatrolHasFinishedeNumber(fireId);
        fireTaskNumberDTO.setPatrolPendingExecute(patrolPendingExecuteNumber);
        fireTaskNumberDTO.setPatrolUnderExecute(patrolUnderExecuteNumber);
        fireTaskNumberDTO.setPatrolHasFinished(patrolHasFinishedeNumber);
        Integer cruisePendingExecuteNumber = appTaskDao.queryCruisePendingExecuteNumber(fireId);
        Integer cruiseUnderExecuteNumber = appTaskDao.queryCruiseUnderExecuteNumber(fireId);
        Integer cruiseHasFinishedeNumber = appTaskDao.queryCruiseHasFinishedeNumber(fireId);
        fireTaskNumberDTO.setCruisePendingExecute(cruisePendingExecuteNumber);
        fireTaskNumberDTO.setCruiseUnderExecute(cruiseUnderExecuteNumber);
        fireTaskNumberDTO.setCruiseHasFinished(cruiseHasFinishedeNumber);
        return fireTaskNumberDTO;
    }

    @Override
    public PageData<Object> queryPatrolTaskByFireId(Long fireId, String status, Integer type, Integer page,
                                                    Integer rows) {
        IPage<AppTask> iPage = new Page<>(page, rows);
        IPage<AppTask> pages = null;
        if (type == 1) {
            //巡护任务
            pages = appTaskDao.queryPatrolTaskByFireId(iPage, fireId, status);
        } else if (type == 2) {
            //巡航任务
            pages = appTaskDao.queryCruiseTaskByFireId(iPage, fireId, status);
        }
        List<AppTask> records = pages.getRecords();
        //2022-05-19 优化 避免过度请求 -------fixed by yzx-------start
        /*records.forEach(e -> {
            Long taskId = e.getId();
            Date endTime = e.getEndTime();
            List<Long> executePersonId = appTaskDao.queryExecutePersonId(taskId);
            if (executePersonId != null && executePersonId.size() != 0) {
                e.setExecutePersonId(executePersonId.get(0));
                e.setExecutePersonName(getRealNameFromFeign(executePersonId.get(0)));
            }
            Date startTime = appTaskDao.queryStartExecuteTime(taskId, null, null);
            e.setStartTime(startTime);
            if (PatrolInfoUtil.isDelay(endTime, e.getFinishTime())) {
                e.setIsDelay(1);
            } else {
                e.setIsDelay(0);
            }
            e.setCreatePersonName(getRealNameFromFeign(e.getCreatePersonId()));
        });*/
        final List<Long> ids = CollUtil.newArrayList();
        records.forEach(e -> {
            Long taskId = e.getId();
            Date endTime = e.getEndTime();
            List<Long> executePersonId = appTaskDao.queryExecutePersonId(taskId);
            if (executePersonId != null && executePersonId.size() != 0) {
                e.setExecutePersonId(executePersonId.get(0));
                ids.add(e.getExecutePersonId());
            }
            Date startTime = appTaskDao.queryStartExecuteTime(taskId, null, null);
            e.setStartTime(startTime);
            if (PatrolInfoUtil.isDelay(endTime, e.getFinishTime())) {
                e.setIsDelay(1);
            } else {
                e.setIsDelay(0);
            }
            ids.add(e.getCreatePersonId());
        });
        final Map<Long, String> idNameMapping = userInfoService.findAndConvertUserInfoByIds(ids);
        records.forEach(e -> {
            e.setCreatePersonName(ObjectUtil.defaultIfNull(idNameMapping.get(e.getCreatePersonId()), StrUtil.EMPTY));
            e.setExecutePersonName(ObjectUtil.defaultIfNull(idNameMapping.get(e.getExecutePersonId()), StrUtil.EMPTY));
        });
        //2022-05-19 优化 避免过度请求 -------fixed by yzx-------end
        PageData<Object> pageData = new PageData<>();
        pageData.setDatas(records);
        pageData.setCount((int) pages.getTotal());
        pageData.setCurrent((int) pages.getCurrent());
        pageData.setSize((int) pages.getSize());
        return pageData;
    }

    @Override
    public PageData<List<AppTask>> querySimplePersonTotalTaskByCondition(Integer page, Integer rows,
                                                                         AppTaskQueryDTO appTaskQueryDTO) {
        IPage<AppTask> iPage = new Page<>(page, rows);
        IPage<AppTask> pages = appTaskDao.querySimplePersonTotalTaskByCondition(iPage, appTaskQueryDTO.getTaskType(),
                appTaskQueryDTO.getStartCreateTime(), appTaskQueryDTO.getEndCreateTime(), appTaskQueryDTO.getStatus(),
                appTaskQueryDTO.getForestkeeperId()
                , appTaskQueryDTO.getStartExecuteTime(), appTaskQueryDTO.getEndExecuteTime());
        List<AppTask> records = pages.getRecords();
        // 处理各种任务类型数据
        handleTaskList(records, appTaskQueryDTO.getTaskType(), appTaskQueryDTO.getStartExecuteTime(),
                appTaskQueryDTO.getEndExecuteTime());
        PageData<List<AppTask>> pageData = new PageData<>();
        pageData.setDatas(pages.getRecords());
        pageData.setCount((int) pages.getTotal());
        pageData.setCurrent((int) pages.getCurrent());
        pageData.setSize((int) pages.getSize());
        return pageData;
    }

    @Override
    public int selectCountByTypeAndStatus(String taskType, List<String> statusList, Long userId) {
        return appTaskDao.selectCountByStatusAndTaskType(statusList, taskType, userId);
    }

    @Override
    public int selectCountByTypeAndStatus1(String taskType, List<String> statusList, List<Long> userIdList) {
        return appTaskDao.selectCountByStatusAndTaskType1(statusList, taskType, userIdList);
    }

    @Override
    public void updateAppTaskByParam(AppTask appTask) {
        if (appTask.getEndTime() != null) {
            appTaskDao.update(
                    new AppTask().setStatus(appTask.getStatus()).setFinishTime(appTask.getFinishTime()).setEndTime(
                            appTask.getEndTime()),
                    new QueryWrapper<AppTask>().eq("id", appTask.getId()));
        } else {
            appTaskDao.update(new AppTask().setStatus(appTask.getStatus()).setFinishTime(appTask.getFinishTime()),
                    new QueryWrapper<AppTask>().eq("id", appTask.getId()));
        }
    }

    /**
     * 处理距离 时长和下达人的参数处理
     *
     * @return
     */
    private List<AppTrackDTO> paramDistanceAndDuration(List<AppTrackDTO> list) {
        //2022-05-19 优化 避免过度请求 -------fixed by yzx-------start
      /*  if (!CollectionUtils.isEmpty(list)) {
            list.forEach(patrolTaskDTO -> {
                patrolTaskDTO.setDistance(HandleStrUtils.handlerDistanceToKm(patrolTaskDTO.getDistance()));
//                patrolTaskDTO.setDuration(TimeUtils.secondsToFormat(patrolTaskDTO.getDuration()));
                String duration = StrUtil.isNotEmpty(patrolTaskDTO.getDuration()) ?
                        NumberUtil.div(NumberUtil.toBigDecimal(patrolTaskDTO.getDuration()), NumberUtil.toBigDecimal("60"), 1).toPlainString() : "0";
                patrolTaskDTO.setDuration(duration);
                patrolTaskDTO.setCreatePersonName(getRealNameFromFeign(patrolTaskDTO.getCreatePersonId()));
            });
        }
        return list;*/
        if (!CollectionUtils.isEmpty(list)) {
            final List<Long> ids = list.stream().map(AppTrackDTO::getCreatePersonId).collect(Collectors.toList());
            //获取接收人数据集合
            com.telit.common.core.utils.Result<Map<Long, MicroSysUserVo>> selectByBatchIdsResult = remoteUpmsService.selectByBatchIds(
                    ids, true);
            Map<Long, MicroSysUserVo> microSysUserVoMap = FeignUtils.unwrap(selectByBatchIdsResult);
            list.forEach(patrolTaskDTO -> {
                patrolTaskDTO.setDistance(HandleStrUtils.handlerDistanceToKm(patrolTaskDTO.getDistance()));
                String duration = StrUtil.isNotEmpty(patrolTaskDTO.getDuration()) ?
                        NumberUtil.div(NumberUtil.toBigDecimal(patrolTaskDTO.getDuration()),
                                NumberUtil.toBigDecimal("60"), 1).toPlainString() : "0";
                patrolTaskDTO.setDuration(duration);
                patrolTaskDTO.setCreatePersonName(
                        microSysUserVoMap.get(patrolTaskDTO.getCreatePersonId()) != null ? microSysUserVoMap.get(
                                patrolTaskDTO.getCreatePersonId()).getRealName() : "");

                // 封装时长，距离，点位集合
                PatrolInfoUtil.setDistantAndDurationAndPointCollection(patrolTaskDTO, patrolTaskDTO.getForestkeeperId(),
                        patrolTaskDTO.getId());
            });
        }
        return list;
        //2022-05-19 优化 避免过度请求 -------fixed by yzx-------end
    }

    /**
     * 根据飞行详情查询无人机code
     *
     * @return
     */
    private AppUavTrackDetail getUavInfoFromFlyDetail(Long userId, Long taskId) {
        DataReturn flyDetail = uavFeignClient.flyingDetail(userId, taskId);
        if (flyDetail.getCode().equals(ResultCode.SUCCESS.getCode()) && flyDetail.getData() != null) {
            return JSON.parseObject(JSON.toJSONString(flyDetail.getData()), AppUavTrackDetail.class);
        }
        return null;
    }

}

